# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://pay.drippayment.com/pay/paymentNet.html'

APP_CONF = {
    '0000315': {
        'API_KEY': 'A0EA941C0B7CB9BA',
    },
    '0000340': {
        'API_KEY': 'FD2D5542F72B250A',
    },
    '0000458': {
        'API_KEY': 'D0F04DB8EA4B1538',
    },
    '0000756': {
        'API_KEY': 'E6AEE06E780FCD86',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_union_sign(parameter, key):
    s = ''
    for k in parameter.keys():
        s += '%s=%s&' % (k, parameter[k])
    s = s[0:len(s) - 1]
    s += key
    _LOGGER.info("dirpay_union sign str: %s", s)
    m = hashlib.md5()
    m.update(s.encode('gbk'))
    sign = m.hexdigest().upper()
    return sign


def generate_union_notify_sign(d, key):
    s = 'versionId={}&businessType={}&insCode={}&merId={}&transDate={}' \
        '&transAmount={}&transCurrency={}&' \
        'orderId={}&ksPayOrderId={}&payStatus={}&payMsg={}&' \
        'pageNotifyUrl={}&backNotifyUrl={}&orderDesc={}&dev={}'.format(
        d['versionId'], d['businessType'], d['insCode'], d['merId'], d['transDate'],
        d['transAmount'], d['transCurrency'],
        d['orderId'], d['ksPayOrderId'], d['payStatus'], d['payMsg'],
        d['pageNotifyUrl'], d['backNotifyUrl'], d['orderDesc'], d['dev']
    )
    s = s + key
    m = hashlib.md5()
    m.update(s.encode('gbk'))
    return m.hexdigest().upper()


def verify_notify_sign(params, key):
    sign = params['signData']
    calculated_sign = generate_union_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("dirpay_union sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def _get_user_phone(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('tel') or '13001234567'


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('versionId', '001'),
        ('businessType', '1100'),
        ('insCode', _get_user_phone(info)),
        ('merId', app_id),
        ('orderId', str(pay.id)),
        ('transDate', local_now().strftime('%Y%m%d%H%M%S')),
        ('transAmount', str(pay_amount)),
        ('transCurrency', '156'),
        ('transChanlName', 'UNIONPAY'),
        ('openBankName', 'bank'),
        ('pageNotifyUrl', '{}/pay/api/{}/dirpay_union/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('backNotifyUrl', '{}/pay/api/{}/dirpay_union/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('orderDesc', 'charge'),
        ('dev', str(pay.id)),
    ))
    parameter_dict['signData'] = generate_union_sign(parameter_dict, api_key)
    parameter_dict['signType'] = 'MD5'
    _LOGGER.info("dirpay_union create charge data: %s ", parameter_dict)
    html_text = _build_form(parameter_dict, _GATEWAY)
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("dirpay_union notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['dev']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('dirpay_union event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['payStatus'])
    trade_no = data['ksPayOrderId']
    total_fee = float(data['transAmount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '00':
        _LOGGER.info('dirpay_union check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pass
